import { useState, useRef } from 'react';
import { useTaskContext } from '../contexts/TaskContext';
import { TaskList, TaskFilterState } from '../components/TaskLibrary/';
import { Task as ComponentTask, Category as ComponentCategory } from '../components/TaskLibrary/types';
import ConfirmDialog from '../components/PopupBox/ConfirmDialog';

export const TaskLibrary = () => {
  const { tasks, loading, addTask, updateTask, deleteTask } = useTaskContext();
  const taskListRef = useRef<{ handleOpenTaskModal: () => void; handleOpenCategoryModal: () => void; } | null>(null);
  
  // 从tasks中提取唯一的分类信息，添加空值检查
  const categories: ComponentCategory[] = Array.from(
    new Set(tasks?.filter(task => task && task.category).map(task => task.category) || [])
  ).map((categoryName, index) => ({
    id: `cat-${index}`,
    name: categoryName
  }));
  
  const [filters, setFilters] = useState<TaskFilterState>({
    searchTerm: '',
    selectedCategory: null
  });

  const [confirmDialog, setConfirmDialog] = useState<{
    open: boolean;
    title: string;
    content: string;
    onConfirm: () => void;
  }>({
    open: false,
    title: '',
    content: '',
    onConfirm: () => {},
  });

  // 过滤任务
  const filteredTasks = tasks.filter((task: ComponentTask) => {
    // 搜索条件筛选
    const matchesSearch = filters.searchTerm === '' || 
      task.taskTitle.toLowerCase().includes(filters.searchTerm.toLowerCase()) ||
      task.taskGuide.toLowerCase().includes(filters.searchTerm.toLowerCase());
    
    // 分类筛选
    const matchesCategory = filters.selectedCategory === null || 
      task.category === filters.selectedCategory;
    
    return matchesSearch && matchesCategory;
  });

  // 更新筛选条件
  const handleFilterChange = (newFilters: Partial<TaskFilterState>) => {
    setFilters(prevFilters => ({
      ...prevFilters,
      ...newFilters
    }));
  };

  // 选择分类
  const handleCategorySelect = (categoryName: string | null) => {
    setFilters(prev => ({
      ...prev,
      selectedCategory: categoryName
    }));
  };

  // 创建Redux风格的dispatch函数
  const dispatchAdapter = (action: any) => {
    switch (action.type) {
      case 'ADD_TASK':
        addTask({
          taskTitle: action.payload.taskTitle,
          taskGuide: action.payload.taskGuide,
          category: action.payload.category
        });
        break;
      case 'UPDATE_TASK':
        updateTask(action.payload.id, {
          taskTitle: action.payload.taskTitle,
          taskGuide: action.payload.taskGuide,
          category: action.payload.category
        });
        break;
      case 'DELETE_TASK':
        deleteTask(action.id);
        break;
      case 'ADD_CATEGORY':
        // 添加新任务时自动创建新类别
        if (!categories.find(cat => cat.name === action.payload.name)) {
          // 创建一个空任务来添加新类别
          addTask({
            taskTitle: `默认任务`,
            taskGuide: '请编辑此任务',
            category: action.payload.name
          });
        }
        break;
      case 'UPDATE_CATEGORY':
        // 更新所有使用该类别的任务
        tasks.forEach(task => {
          if (task.category === action.payload.oldName) {
            updateTask(task.id, {
              ...task,
              category: action.payload.newName
            });
          }
        });
        break;
      case 'DELETE_CATEGORY':
        // 删除该类别下的所有任务
        tasks.forEach(task => {
          if (task.category === action.payload.name) {
            deleteTask(task.id);
          }
        });
        break;
      default:
        console.warn('Unknown action type:', action.type);
    }
  };

  // 处理删除类别
  const handleDeleteCategory = (categoryName: string) => {
    const taskCount = tasks.filter((t: ComponentTask) => t.category === categoryName).length;
    
    setConfirmDialog({
      open: true,
      title: '确认删除类别',
      content: `确定要删除类别 "${categoryName}" 吗？这将同时删除该类别下的 ${taskCount} 个任务。`,
      onConfirm: () => {
        dispatchAdapter({
          type: 'DELETE_CATEGORY',
          payload: { name: categoryName }
        });
        // 如果当前选中的就是要删除的类别，重置选中状态
        if (filters.selectedCategory === categoryName) {
          handleCategorySelect(null);
        }
        setConfirmDialog(prev => ({ ...prev, open: false }));
      }
    });
  };

  return (
    <div className="w-full">
      {/* 头部 */}
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-3xl font-bold text-gray-900 dark:text-white">任务库</h1>
      </div>

      {/* 搜索框部分 */}
      <div className="mb-6">
        <div className="relative">
          <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
            <svg className="h-5 w-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
            </svg>
          </div>
          <input
            type="text"
            placeholder="搜索任务..."
            className="w-full pl-10 pr-4 py-3 border border-gray-300 dark:border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white dark:bg-gray-800 text-gray-900 dark:text-white"
            value={filters.searchTerm}
            onChange={(e) => handleFilterChange({ searchTerm: e.target.value })}
          />
        </div>
      </div>

      {/* 内容区域 - 分类列表和任务列表并排 */}
      <div className="flex flex-col md:flex-row gap-6">
        {/* 左侧分类列表 */}
        <div className="w-full md:w-64 flex-shrink-0">
          <div className="flex justify-between items-center mb-2">
            <h2 className="text-lg font-semibold text-gray-900 dark:text-white">类别</h2>
            <button 
              className="text-gray-400 hover:text-gray-500 dark:text-gray-300 dark:hover:text-gray-200"
              onClick={() => taskListRef.current?.handleOpenCategoryModal()}
            >
              <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
              </svg>
            </button>
          </div>
          <ul className="space-y-1">
            <li>
              <button
                className={`w-full flex items-center justify-between px-3 py-2 rounded-md ${filters.selectedCategory === null ? 'bg-gray-100 dark:bg-gray-800 font-medium' : 'hover:bg-gray-50 dark:hover:bg-gray-800'} text-gray-900 dark:text-white`}
                onClick={() => handleCategorySelect(null)}
              >
                <div className="flex items-center">
                  <svg className="w-5 h-5 mr-2 text-gray-500 dark:text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
                  </svg>
                  所有任务
                </div>
                <span className="text-gray-500 dark:text-gray-400 text-sm">{tasks.length}</span>
              </button>
            </li>
            {categories.map((category: ComponentCategory) => {
              const taskCount = tasks.filter((t: ComponentTask) => t.category === category.name).length;
              return (
                <li key={category.id}>
                  <div className={`w-full flex items-center justify-between px-3 py-2 rounded-md ${filters.selectedCategory === category.name ? 'bg-gray-100 dark:bg-gray-800' : 'hover:bg-gray-50 dark:hover:bg-gray-800'} text-gray-900 dark:text-white group`}>
                    <button
                      className="flex-1 flex items-center"
                      onClick={() => handleCategorySelect(category.name)}
                    >
                      <div className="flex items-center">
                        <svg className="w-5 h-5 mr-2 text-gray-500 dark:text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" />
                        </svg>
                        {category.name}
                      </div>
                      <span className="ml-2 text-gray-500 dark:text-gray-400 text-sm">{taskCount}</span>
                    </button>
                    <button
                      onClick={() => handleDeleteCategory(category.name)}
                      className="opacity-0 group-hover:opacity-100 ml-2 p-1 text-gray-400 hover:text-red-500 dark:text-gray-500 dark:hover:text-red-400 rounded"
                    >
                      <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                      </svg>
                    </button>
                  </div>
                </li>
              );
            })}
          </ul>
        </div>

        {/* 右侧任务列表 */}
        <div className="flex-1">
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-lg font-semibold text-gray-900 dark:text-white">
              {filters.selectedCategory ? filters.selectedCategory : "所有任务"}
            </h2>
            {loading && <span className="text-gray-500">加载中...</span>}
          </div>
          <TaskList 
            ref={taskListRef}
            tasks={filteredTasks}
            categories={categories}
            dispatch={dispatchAdapter}
          />
        </div>
      </div>

      <ConfirmDialog
        open={confirmDialog.open}
        title={confirmDialog.title}
        content={confirmDialog.content}
        onConfirm={confirmDialog.onConfirm}
        onCancel={() => setConfirmDialog(prev => ({ ...prev, open: false }))}
      />
    </div>
  );
}; 